package com.app.library.base

import android.app.AlertDialog
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModel
import androidx.viewbinding.ViewBinding
import com.app.library.utils.ViewBindingUtil
import com.app.library.utils.ViewModelUtils
import com.blankj.utilcode.util.KeyboardUtils

/**
 * 基类
 */
abstract class LibDialogFragment<VB : ViewBinding, VM:ViewModel> : DialogFragment() {

    lateinit var binding: VB
    lateinit var mModel: VM

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        binding = ViewBindingUtil.inflateWithGeneric(this, LayoutInflater.from(context))
        val style = getStyle()
        val builder = if (style == null) {
            AlertDialog.Builder(requireActivity())
        } else {
            AlertDialog.Builder(requireActivity(), style)
        }
        builder.setView(binding.root)
        val alertDialog = builder.create()
        alertDialog.setCanceledOnTouchOutside(isCanceledTouchOutside())
        val window = alertDialog.window
        window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        mModel = ViewModelUtils.getWithGeneric(this)
        initView()
        return alertDialog
    }

    abstract fun initView()

    fun showNow(manager: FragmentManager) {
        showNow(manager, javaClass.simpleName)
    }


    open fun getStyle(): Int? {
        return null
    }

    override fun onStart() {
        super.onStart()
        val dialog = dialog
        if (dialog != null) {
            val dm = DisplayMetrics()
            activity?.windowManager?.defaultDisplay?.getMetrics(dm)
            dialog.window?.setLayout(
                (dm.widthPixels * getWidthRatio()).toInt(),
                getHeight()
            )
            dialog.window?.setGravity(getGravity())
            getBgAlpha()?.let {
                dialog.window?.setDimAmount(it)
            }
        }
    }

    override fun dismissAllowingStateLoss() {
        KeyboardUtils.hideSoftInput(dialog?.window)
        super.dismissAllowingStateLoss()
    }

    /**
     * 占屏幕宽度比例
     */
    protected open fun getWidthRatio(): Float {
        return 0.85f
    }

    /**
     * 背景透明度
     */
    protected open fun getBgAlpha(): Float? {
        return null
    }

    /**
     * 高度
     */
    open fun getHeight(): Int {
        return ViewGroup.LayoutParams.WRAP_CONTENT
    }

    /**
     * 位置
     */
    open fun getGravity(): Int {
        return Gravity.CENTER
    }

    open fun isCanceledTouchOutside(): Boolean {
        return false
    }
}